package cn.js.sangu.unitStore.controller;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import cn.hutool.core.date.DateUtil;
import cn.js.sangu.unitStore.common.LogType;
import cn.js.sangu.unitStore.common.MyLogsAOP;
import cn.js.sangu.unitStore.common.R;
import cn.js.sangu.unitStore.common.constant.SysInfo;
import cn.js.sangu.unitStore.entity.MessageBox;
import cn.js.sangu.unitStore.service.MessageBoxService;
import lombok.extern.slf4j.Slf4j;

/**
 * 说明：消息信箱
 * 作者：linshuo
 * 日期：2024/8/7 8:40
 */
@Slf4j
@RequestMapping("messageBox")
@RestController
public class MessageBoxController {

    static final String OPERATION_MESSAGE = "消息管理";

    @Autowired
    MessageBoxService messageBoxService;

    /**
     * 获取消息详情
     * 
     * @param id 消息ID
     * @return 消息详情
     */
    @MyLogsAOP(operation = OPERATION_MESSAGE, operaType = LogType.LOOKUP)
    @GetMapping("detail/{id}")
    public R detail(@PathVariable String id) {
        log.info("获取消息详情，消息ID: {}", id);
        try {
            MessageBox message = messageBoxService.getById(id);
            if (message == null) {
                log.warn("消息不存在，消息ID: {}", id);
                return R.fail("消息不存在");
            }
            log.info("获取消息详情成功，消息ID: {}", id);
            return R.ok(message);
        } catch (Exception e) {
            log.error("获取消息详情失败，消息ID: {}", id, e);
            return R.fail("获取消息详情失败");
        }
    }

    /**
     * 获取消息列表
     * 
     * @param userId 用户ID
     * @return 消息列表
     */
    @MyLogsAOP(operation = OPERATION_MESSAGE, operaType = LogType.LOOKUP)
    @GetMapping("list")
    public R list(String userId) {
        log.info("获取消息列表，用户ID: {}", userId);
        try {
            // 获取当前用户的所有消息，限制100条
            List<MessageBox> messages = messageBoxService.getAllMessages(userId, 100, 0);
            log.info("获取消息列表成功，共{}条记录", messages.size());
            return R.ok(messages);
        } catch (Exception e) {
            log.error("获取消息列表失败", e);
            return R.fail("获取消息列表失败");
        }
    }

    /**
     * 更新消息已读状态
     * 
     * @param message 消息对象，包含消息ID
     * @return 操作结果
     */
    @MyLogsAOP(operation = OPERATION_MESSAGE, operaType = LogType.UPDATE)
    @PostMapping("read")
    @Transactional(rollbackFor = Exception.class)
    public R updateReadStatus(@RequestBody Map<String, String> requestBody) {
        String messageId = requestBody.get("id");
        if (messageId == null || messageId.trim().isEmpty()) {
            log.warn("消息ID为空");
            return R.fail("消息ID不能为空");
        }
        log.info("更新消息已读状态，消息ID: {}", messageId);
        // 参数校验已通过@Valid注解完成
        MessageBox msg = messageBoxService.getById(messageId);
        if (msg == null) {
            log.warn("消息不存在，消息ID: {}", messageId);
            return R.fail("消息不存在");
        }

        // 检查是否已经标记为已读
        if (msg.getIsRead() != null && msg.getIsRead() == SysInfo.ReadingStatusIsread) {
            log.info("消息已标记为已读，无需重复操作，消息ID: {}", messageId);
            return R.ok("消息已标记为已读");
        }

        // 更新已读状态
        msg.setIsRead(SysInfo.ReadingStatusIsread);
        msg.setMsgTime(DateUtil.now()); // 设置已读时间
        boolean updated = messageBoxService.updateById(msg);

        if (updated) {
            log.info("消息已读状态更新成功，消息ID: {}", messageId);
            return R.ok("消息已标记为已读");
        } else {
            log.error("消息已读状态更新失败，消息ID: {}", messageId);
            return R.fail("消息已读状态更新失败");
        }
    }

    /**
     * 删除用户的全部消息
     * 
     * @param userId 用户ID
     * @return 操作结果
     */
    @MyLogsAOP(operation = OPERATION_MESSAGE, operaType = LogType.DELETE)
    @DeleteMapping("deleteAll")
    @Transactional(rollbackFor = Exception.class)
    public R deleteAll(@RequestParam("userId") String userId) {
        log.info("删除用户全部消息，用户ID: {}", userId);

        if (userId == null || userId.trim().isEmpty()) {
            log.warn("用户ID为空");
            return R.fail("用户ID不能为空");
        }

        try {
            // 根据用户ID删除所有消息
            boolean deleted = messageBoxService.removeByUserId(userId);

            if (deleted) {
                log.info("用户全部消息删除成功，用户ID: {}", userId);
                return R.ok("所有消息已删除");
            } else {
                log.warn("用户消息删除失败或该用户无消息，用户ID: {}", userId);
                return R.fail("删除消息失败");
            }
        } catch (Exception e) {
            log.error("删除用户全部消息失败，用户ID: {}", userId, e);
            return R.fail("删除消息失败");
        }
    }

}
